package servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.UserDao;

import entity.User;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

	private UserDao userDao = new UserDao();

	String rand;
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		doPost(req, resp);

	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");// 这是一个坑，前端传数据进来，要先判断它编码是否正确
		// 1、获取请求参数
		String uname = req.getParameter("uid");
		String pwd = req.getParameter("pwd");
		HttpSession session = req.getSession();
		System.out.println(uname);
		System.out.println(pwd);
//		//设置验证码
//		rand = getFourRandom();
//		req.setAttribute("reg", rand);
//		session.setAttribute("reg", rand);
//		System.out.println(rand);
//		//获取验证码
//		String abc = (String) session.getAttribute("reg");
//		System.out.println("abc = " + abc);
		// 2、调用userService.login()登录处理业务
		User loginUser = login(new User(uname, pwd));

		if (req.getCookies() != null) {// 判断当前的request中是否有cookie
			Cookie[] cookies = req.getCookies();
			for (Cookie c : cookies) {
				if ("uname".equals(c.getName())) {// 选择cookie指定的key值
					req.setAttribute("uid", c.getValue());
				}
				if ("pwd".equals(c.getName())) {
					req.setAttribute("pwd", c.getValue());
				}
			}
		} else {

		}


		// 如果loginUser = null说明 登录失败
		if (loginUser == null) {
			// 跳回登录页面
			System.out.println("登录失败!!!");
			req.getRequestDispatcher("login.jsp").forward(req, resp);
		} else {
			int ud = loginUser.getUid();
			String uid = Integer.toString(ud);
			// 创建cookie
			Cookie cookie1 = new Cookie("uname", uname);
			Cookie cookie2 = new Cookie("pwd", pwd);
			cookie1.setMaxAge(60 * 60);// 60*60秒 一小时
			cookie2.setMaxAge(60 * 60);
			cookie1.setPath("/");
			cookie2.setPath("/");

			// 将cookie存到response，取值通过request来获取
			resp.addCookie(cookie1);
			resp.addCookie(cookie2);

			// 存到Session域
			session.setAttribute("uid", uid);
			session.setAttribute("req", 1);

			// 存到请求域
			req.setAttribute("uid", uid);
			req.setAttribute("pwd", pwd);
			// 登录成功 跳到index.jsp
			System.out.println("切换主页页面");

			resp.sendRedirect("index"); // 可改变地址栏，重定向，新建对象，不能setAttribute传参，可通过session获取 两次请求
		}
	}

	// 登录
	public User login(User user) {
		return userDao.queryByNameAndPassword(user.getUname(), user.getPwd());
	}

	/**
	 * 产生4位随机数(0000-9999)
	 * 
	 * @return 4位随机数
	 */
	public static String getFourRandom() {
		Random random = new Random();
		String fourRandom = random.nextInt(10000) + "";
		int randLength = fourRandom.length();
		if (randLength < 4) {
			for (int i = 1; i <= 4 - randLength; i++)
				fourRandom = "0" + fourRandom;
		}
		return fourRandom;
	}

}
